using System;
using System.Collections;
using System.Windows.Forms;

namespace ASA
{
	public class ListViewItemComparer : IComparer
	{
		DataType sortType;
		int sortColumn;
		bool bAscending;

		public ListViewItemComparer()
		{
			sortType = DataType.String;
			sortColumn = 0;
			bAscending = true;
		}
		public ListViewItemComparer(int sortColumn, bool bAscending, DataType sortType)
		{
			this.sortColumn = sortColumn;
			this.bAscending = bAscending;
			this.sortType = sortType;
		}
		public int Compare(object ox, object oy)
		{
			int compareResult = 0;
			ListViewItem x = (ListViewItem)ox;
			ListViewItem y = (ListViewItem)oy;
			
			try
			{
				if (sortType == DataType.String || 
					sortType == DataType.Boolean || 
					x.SubItems[sortColumn].Text == "" || y.SubItems[sortColumn].Text == "")
				{
					compareResult = String.Compare(x.SubItems[sortColumn].Text, y.SubItems[sortColumn].Text);
				}
				else if (sortType == DataType.Currency)
				{
					string xString = x.SubItems[sortColumn].Text;
					string yString = y.SubItems[sortColumn].Text;

					if (xString.Length > 0)
					{
						if (xString[0] == '(')
						{
							xString = xString.Remove(0, 2); // remove starting ($
							xString = xString.Remove(xString.Length-1, 1); // remove ending )
							xString = '-' + xString;
						}
						else
							xString = xString.Remove(0, 1); // remove starting $
					}

					if (yString.Length > 0)
					{
						if (yString[0] == '(')
						{
							yString = yString.Remove(0, 2); // remove starting ($
							yString = yString.Remove(yString.Length-1, 1); // remove ending )
							yString = yString = '-' + yString;
						}
						else
							yString = yString.Remove(0, 1); // remove starting $
					}

					compareResult = Double.Parse(xString).CompareTo(Double.Parse(yString));
				}
				else if (sortType == DataType.Date)
				{
					compareResult = DateTime.Parse(x.SubItems[sortColumn].Text).CompareTo(DateTime.Parse(y.SubItems[sortColumn].Text));
				}
				else if (sortType == DataType.Double)
				{
					compareResult = Double.Parse(x.SubItems[sortColumn].Text).CompareTo(Double.Parse(y.SubItems[sortColumn].Text));
				}
				else if (sortType == DataType.Integer)
				{
					compareResult = Int32.Parse(x.SubItems[sortColumn].Text).CompareTo(Int32.Parse(y.SubItems[sortColumn].Text));
				}

				if (bAscending)
					return compareResult;
				else
					return (-compareResult);
			}
			catch (Exception err)
			{
				System.Diagnostics.Trace.WriteLine("Format error in a record. --> " + err.Message);
				return 1;
			}
		}
		public int SortColumn
		{
			set
			{
				sortColumn = value;
			}
			get
			{
				return sortColumn;
			}
		}
        public enum DataType
        {
            Boolean,
            Currency,
            Date,
            Double,
            Integer,
            String
        }
	}
}